<?php
namespace addon\wechat_config\logic;
// +----------------------------------------------------------------------
// | Author: xiaojun <920668625@qq.com>
// +----------------------------------------------------------------------
use app\common\logic\LogicBase;
use think\Db;
use \tpfcore\Core;
use tpfcore\web\Curl;
use think\Cache;
use tpfcore\helpers\StringHelper;
use addon\wechat_config\logic\WechatFunc;
class Wechat extends LogicBase
{
	public function getUserInfo($data){

		if(empty($data['code'])) return [-1,"非法请求"];

        $code  = $data['code'];

        $info = Db::name('WechatConfig')->order('id desc')->value('value');
        $info = json_decode($info,true);

    	if(empty($info) || empty($info['wechat_appid']) || empty($info['wechat_appsecret'])){
    		throw new \Exception("请先配置好微信公众号");exit;
    	}

    	$appid     = $info['wechat_appid'];
        $secret = $info['wechat_appsecret'];

        // 第二步：通过code换取网页授权access_token
        $access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
        $res = json_decode(Curl::get($access_token_url));

        if (!empty($res->errcode)) {
            return [$res->errcode, 'error', (array)$res];
        }

        // 第三步：刷新access_token（如果需要,本人觉得很多余）

        // 第四步：拉取用户信息(需scope为 snsapi_userinfo)
        $access_token = $res->access_token;

        $openid = $res->openid;

        /* 
            静默授权的方式
        */
        $access_token_global = WechatFunc::getAccessToken();

        $user_info_user = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token_global&openid=$openid";

        /*
        网页授权的方式
        $user_info_user ="https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid";
        $user_info = json_decode(Curl::get($user_info_user));
        */

        return [0,"success",json_decode(Curl::get($user_info_user),true)];
	}
    /**
    * type 获取二维码的类型   1临时   2永久
    * @param type int 二维码类型 可选 值 1或2
    * @param expire int 有效期 临时二维码有效，非负数 可选
    * @param scene_value string|int 场景值 必须 
    */
    public function getExtendQrcode($data){
        $type = isset($data['type']) && $data['type']==1?1:2;
        $expire = isset($data['expire']) && is_numeric($data['expire']) && $data['expire']>0 && $data['expire']<2592000?$data['expire']:2592000;  //临时二维码有效果
        if(empty($data['scene_value']) || (!is_numeric($data['scene_value']) && !is_string($data['scene_value']))) {
            return [-40049,"场景值非法"];
        }
        try{
            $token = WechatFunc::getAccessToken();
        } catch (\Exception $e) {
            return [40049,$e->getMessage(),null];
        }
        switch ($type) {
            case 1:
                $param = is_numeric($data['scene_value'])?'{"expire_seconds":'.$expire.',"action_name":"QR_SCENE","action_info":{"scene":{"scene_id":'.$data['scene_value'].'}}}':'{"expire_seconds":'.$expire.', "action_name": "QR_STR_SCENE", "action_info": {"scene": {"scene_str": "'.$data['scene_value'].'"}}}';
                break;
            
            default:
                $param=is_numeric($data['scene_value'])?'{"action_name":"QR_LIMIT_SCENE","action_info":{"scene":{"scene_id":'.$data['scene_value'].'}}}':'{"action_name": "QR_LIMIT_STR_SCENE", "action_info": {"scene": {"scene_str": "'.$data['scene_value'].'"}}}';
                break;
        }
        $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$token;
        $output = json_decode(WechatFunc::http_request($url,$param),true);
        if(isset($output['errcode'])){
            return [40049,'操作失败['.$output['errcode'].']',null];
        }else{
            return [0,"success","https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($output['ticket'])];
        }
    }
}